package com.wechat.wins.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientImpl implements HttpClient {

    Logger logger = LoggerFactory.getLogger(HttpClientImpl.class);

    @Override
    public String sendGet(final String url, final Map<String, Object> params) {
        final StringBuilder sb = new StringBuilder();
        BufferedReader in = null;
        try {
            final URL fullUrl = new URL(url+"?"+buildRequestParams(params));
            final URLConnection conn = fullUrl.openConnection();
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0");
            conn.connect();
            final Map<String, List<String>> map = conn.getHeaderFields();
            // 遍历所有的响应头字段
            for (final String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
        } catch (final MalformedURLException e) {
            e.printStackTrace();
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (final Exception e2) {
                e2.printStackTrace();
            }
        }
        return sb.toString();
    }

    private String buildRequestParams(final Map<String, Object> params) {
        final StringBuilder builder = new StringBuilder();
        for (final Map.Entry e : params.entrySet()) {
            builder.append(e.getKey()).append('=').append(e.getValue()).append('&');
        }
        return builder.deleteCharAt(builder.length()-1).toString();
    }

    @Override
    public String sendPost(final String url, final Map<String, Object> params) {
        final String result = "";
        return result;
    }
}
